// pages/finish/finish.js
import {request} from '../../request/index.js'
import {upload} from '../../utils/qiniuUploader'
import regeneratorRuntime, { async } from '../../lib/runtime/runtime';
import Notify from '../../vant/dist/notify/notify'
// import Toast from '../../vant/dist/toast/toast'
Page({

  /**
   * 页面的初始数据
   */
  data: {
     // 预览
     fileList: [],
     chkMin: '',
    //  消除隐患
     chkForm: {
      chkId: '',
      chkType: '',
      chkInfo: '',
      chkLng: '',
      chkLat: ''
     },
     IsFinal: false,
     IsGener:true,
     day: '', // 巡视持续时间/天时分秒
     minutes: '',
     hours: '',
     seconds: '',
     endTime: '',
     uploadToken: '', // 七牛云上传存储
     tempFilePaths: '',
     imgList: [], // 上传成功的图片数组
     textValue: '', // 隐患描述
  },

  // 进入消除隐患申请
  changeType: function(e){
    this.setData({
      IsFinal: true,
      IsGener: false,
      "chkForm[0].chkType":'final'
    })
    Notify({
      message: "您已选择申请消除隐患，\n 若要取消，\n请单击取消按钮",
      color: '#ffffff',
      background: '#467072',
      duration: 4500,
    });
    console.log(this.data.chkForm[0].chkType)
  },
  changeType1: function(e){
    this.setData({
      IsFinal: false,
      IsGener: true,
      "chkForm[0].chkType":'general'
    })
    Notify({
      message: "您已取消申请",
      color: '#ffffff',
      background: '#9c9c9c'
    });
    console.log(this.data.chkForm[0].chkType)
  },
  // 文件上传完毕回调函数after-read
  afterRead(event) {
    const { file } = event.detail; // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    this.setData({
        fileList:[...this.data.fileList, ...file]
    })
    console.log(this.data.fileList)
    // this.uploadImg(file[0].url);
  },

  // 删除图片
  delete(event) {
    // console.log(event)
    let imgDelIndex = event.detail.index
    let fileList = this.data.fileList
    fileList.splice(imgDelIndex,1)
    console.log('删除图片的',fileList)
    this.setData({
        fileList
    })
    // this.uploadImg(fileList)
  },
  msInput(event) {
    this.setData({
      textValue: event.detail
    })
    console.log(this.data.textValue)
  },
  async uploadImg(){
    // 有图片上传则七牛云 
  if (this.data.fileList[0]){
    wx.showLoading({
      title: '玩命上传中',
    })
    const res = await request({
      url: '/other/upload',
      header:{
        'Authorization':'Bearer '+wx.getStorageSync('token'),
      },
      method: "get",
    })
    console.log(res)
    let _this = this
    if (res.data.status === 200 ) {
      _this.setData({
          uploadToken: res.data.data.uploadToken
      }, () => {
         var filepath = _this.data.fileList
         console.log(filepath)
        for (var i = 0 ; i< filepath.length ; i++){
          var file = filepath[i].url
          console.log(file)
           upload(file, res => {
            console.log(res)
            _this.setData({
              tempFilePaths:'https://ele.qiniu.heilama.com' +"/"+ res.key,
              imgList: _this.data.imgList.concat("http://ele.qiniu.heilama.com" + "/" + res.key),
            },()=>{
              console.log(_this.data.tempFilePaths)
              console.log("imgList" + _this.data.imgList),
              console.log(_this.data.imgList.length)
              if (filepath.length === _this.data.imgList.length){
                console.log('七牛云上传完毕')
                var photo = _this.data.imgList
                var strphoto = photo.toString(',')
                var content = _this.data.textValue
                var info = content + 'imgGroup:' + strphoto
                console.log(info)
                console.log(_this.data.fileList)
                _this.setData({
                  "chkForm[0].chkInfo": info
              },() => {
                wx.hideLoading()
                _this.SendToFinal()
              })
              }
            })
          }, (error) => {
            console.log('error' + error)
          }, {
          //这里是你所在大区的地址
            uploadURL: 'https://up-z2.qiniup.com',
            // domain: 'qm94gq3eu.hn-bkt.clouddn.com',
            // domain: 'https://ele.qiniu.heilama.com',
            domain: 'ele.qiniu.heilama.com',
      //这里的uptoken是后端返回来的
            uptoken: _this.data.uploadToken,
          })
          }
      })
    }
  }
  else {
    this.setData({
      "chkForm[0].chkInfo": this.data.textValue,
    },() => {
      this.SendToFinal()
    })
  }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // this.Check();
    this.setData({
      // day: options.day,
      // hours: options.hours,
      // minutes: options.minutes,
      // seconds: options.seconds,
      // updateTime: options.updateTime,
      endTime: options.endTime,
      chkMin: options.chkMin,
      "chkForm[0].chkLng": options.chkLng,
      "chkForm[0].chkLat": options.chkLat,
      "chkForm[0].chkId": options.chkId,
      "chkForm[0].chkType":'general',
    },() => {
      wx.removeStorageSync('checkDgeId')
    })
    // this.setData({
    //   Id: options.Id
    // })
    console.log(options)
  },
// 巡视记录
async SendToFinal(){
    console.log(this.data.chkForm[0])
    const res = await request({
    url: '/check/update/',
    header:{
      'Authorization':'Bearer '+wx.getStorageSync('token'),
    },
    data: this.data.chkForm[0],
    method: "put",
  })
  console.log(res)
  if (res.data.status !== 200){
    var title = res.data.msg
    wx.showToast({
      title: title,
      icon: 'none',
      duration: 1500
    })
    setTimeout(function(){
      wx.redirectTo({
        url: '/pages/fail/fail',
      })
    },1500)
  }
  else {
    wx.showToast({
      title: '上传成功',
      icon: 'success',
      duration: 1500
    })
    setTimeout(function(){
      wx.redirectTo({
        url: '/pages/success/success',
      })
    },1500)
  }
},
// 按编号查看巡视记录
// async Check(){
//   if (this.data.Id) {
//     const res = await request({
//       url: '/check/findById/'+ this.data.Id ,
//       header:{
//         'Authorization':'Bearer '+wx.getStorageSync('token'),
//       },
//       method: "get",
//     })
//     // console.log(res)
//     if (res.data.status !== 200){
//       var title = res.data.msg
//       wx.showToast({
//         title: title,
//         icon: 'none',
//         duration: 2000
//       })
//       setTimeout(function(){
//         wx.navigateTo({
//         url: '/pages/my/my',
//       })
//       },3000)
//     }else{
//       var list = res.data.data
//       console.log(list)
//       this.setData({
//         updateTime: list.updateTime,
//         createTime: list.createTime,
//         "chkForm[0].chkLng": list.chkLng,
//         "chkForm[0].chkLat": list.chkLat,
//         "chkForm[0].chkId": list.chkId
//       },() => {
//         this.calculationDate(this.data.createTime,this.data.updateTime)
//       })
//     }
//   }
//   else {
//     Toast.fail('好像哪里出错了，\n 请联系管理员');
//     setTimeout(function(){
//       wx.navigateTo({
//       url: '/pages/my/my',
//     })
//     },3000)
    
//   }
// },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if ( wx.getStorageSync('token')){
      this.checkToken()
    }
    else {
      wx.reLaunch({
        url: '/pages/index/index',
      })
    }
  },
  async checkToken(){
    var token = wx.getStorageSync('token')
    if (token){
      const res = await request({
        url: '/user/verify',
        header:{
          'Authorization':'Bearer '+ token,
        },
        method: "get",
      })
      if (res.data.status !== 200){
         var title = res.data.msg ? res.data.msg :null
        if (title){
        wx.showToast({
          title: title,
          icon: 'none',
          duration: 2000
          })
        wx.reLaunch({
          url: '/pages/index/index'
        });
      }
    } 
  }
},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})